<template>
  <div class="withdraw" ref="withdraw">
    <div class="topTitle">
      <title-item title1st="待提现佣金" :subTitle="dataCounts.money ? `￥${dataCounts.money}` : ''">
      </title-item>
    </div>
    <div class="borderdiv"></div>
    <!-- <div class="selectVal">
      <div class="time show-box" @click="selectTime">
        <van-icon name="underway-o" style="margin-right: 5px" />{{
          dateRange ? dateRange : "选择时间范围"
        }}<van-icon
          name="cross"
          style="margin: 0 0px 0 5px"
          @click.stop="onCancel"
          v-if="dateRange"
        />
      </div>
       <div class="right">
        <div class="show-box downList" @click="actionList">生成对账清单</div>
        <div class="show-box" @click="downExcel">下载</div>
      </div> 
    </div> -->
    <!-- <div class="item">
      <div class="">待提现佣金</div>
      <div class="jeNum">￥{{ dataCounts.money }}</div>
    </div> -->
    <div class="item">
      <div class="">提现方式</div>
      <div class="txType">
        <van-icon name="chat" color="#2CB9A4" size="24" />
        <text class="useFunc">微信钱包</text>
        <van-icon name="arrow" />
      </div>
    </div>
    <div class="item">
      <text class="u-demo-block__title">提现金额:</text>
    </div>
    <div class="txje item">
      <van-field v-model="price" placeholder="请输入金额" input-align="left" :border="true" :disabled="false" />
    </div>
    <div class="item">
      <text class="u-demo-block__title">支付宝账号:</text>
    </div>
    <div class="txje item">
      <van-field v-model="alipayAccount" placeholder="请输入支付宝账号" input-align="left" :border="true" />
    </div>
    <div class="item info">
      提现说明：当日最高提现金额：{{ config.highest_money }}元,最低提现金额{{
        config.minimum_money
      }}元,提现手续费：{{ config.commission }}%
    </div>
    <div class="borderdiv item"></div>
    <div class="botBtn">
      <div style="width: 100%" @click="withMoney">
        <!-- <u-button class="custom-style" text="提现"
					customStyle=" background:linear-gradient(90deg, #218CC9 0%, #2CB9A4 100%);color:#fff;margin-top:50px;border-radius: 30px;"
					@click="goAuth">
				</u-button> -->
        <van-button color="linear-gradient(90deg, #218CC9 0%, #2CB9A4 100%)" block round="true">
          提现
        </van-button>
      </div>
    </div>
    <van-popup v-model:show="showPicker" position="bottom">
      <van-picker-group title="预约日期" :tabs="['开始日期', '结束日期']" @confirm="onConfirm" @cancel="onCancel">
        <van-date-picker v-model="startDate1" :min-date="minDate" :max-date="maxDate" />
        <van-date-picker v-model="endDate1" :min-date="minDate" :max-date="maxDate" />
      </van-picker-group>
    </van-popup>
    <van-overlay :show="show" @click="show = false">
      <div class="wrapper">点击右上角，用浏览器打开下载<span>↪</span></div>
    </van-overlay>
  </div>
</template>

<script setup>
import TitleItem from "@/components/title-item/title-item.vue";
import useMainStore from "@/stores/modules/main";
import {
  getRegionservice,
  reconciliation,
  getConfig,
  getMoney,
  initiate,
  getOpenid,
} from "@/services";
import { computed } from "@vue/reactivity";
import { showToast, showConfirmDialog } from "vant";
import { onMounted, watch, ref } from "vue";
import { amountCer } from "@/utils/format_money";
// console.log(amountCer,'amountCer')
import { formatMonthDay, getDiffDays } from "@/utils/format_date";
import {
  isWxBrowser,
  resolveBlob,
  getCode,
  copyText,
} from "@/utils/uploadFun.js";
// console.log(isWxBrowser())
const mainStore = useMainStore();
import { storeToRefs } from "pinia";
import { reactive } from "vue";
const price = ref("");
const { dataCounts } = storeToRefs(mainStore);
// price.value = dataCounts.money//默认提现的就是所有
const dateRange = ref("");
const show = ref(false);
let downPath = "";
const { startDate, endDate } = storeToRefs(mainStore);
const startDateStr = computed(() =>
  formatMonthDay(startDate.value, "YYYY,MM,DD")
);
//以下内容是新增的判断是否已经绑定openid
import ClipboardJS from "clipboard"; //引入粘贴插件
import useUserInfo from "@/stores/modules/userInfo";
import { useRouter } from "vue-router";
const router = useRouter();
const userStore = useUserInfo();
const { is_wx } = storeToRefs(userStore);
console.log(is_wx.value, "卡经销商");
const getWxInfo = async () => {
  if (is_wx.value) return false;
  if (is_wx.value == 0 && !is_wx.value) {
    //未绑定的时候
    let data = getCode();
    if (!data.isWx) {
      //不是微信环境
      showConfirmDialog({
        title: "提示",
        className: "copyInfo",
        confirmButtonColor: "#218CC9",
        message: `复制链接，去微信打开公众号操作！`,
      })
        .then(async () => {
          // copyText('https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=Mzg5MDk0NjQ2Mw==#wechat_redirect')
          // setTimeout(() => {
          //   showToast('已复制链接到剪切板')
          // }, 200)
          const clipboardText = ref(
            "https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=Mzg5MDk0NjQ2Mw==#wechat_redirect"
          );
          const copyText = () => {
            const clipboard = new ClipboardJS(".copyInfo .van-button", {
              text() {
                return clipboardText.value;
              },
            });
            clipboard.on("success", () => {
              showToast("已复制链接到剪切板");
            });
            clipboard.on("error", () => {
              console.log("复制失败");
            });
          };
          copyText();
        })
        .catch(() => {
          // on cancel
        });
    } else {
      //是微信环境
      //
      if (data.code) {
        //存在code的时候此时要绑定微信用户
        let res = await getOpenid({ code: data.code });
        //成功之后再回调一次
        userStore.getInfo();
        // console.log(is_wx.value,'此时应该为1才正确')
        console.log(res, "绑定微信openid的状态");
        if (res.code === 200) {
          //此时一般都是code失效
          userStore.is_wx = 1;
          const urlParams = new URL(window.location.href); //将字符串变成url对象
          let url = urlParams.origin + urlParams.pathname + "/#/withdraw";
          location.href = url;
        }
        if (res.msg == "code失效") {
          //此时一般都是code失效
          const urlParams = new URL(window.location.href); //将字符串变成url对象
          let url = urlParams.origin + urlParams.pathname + "/#/withdraw";
          location.href = url;
        }
        // if(res.code === 0){//此时一般都是code失效
        //   const urlParams = new URL(window.location.href);//将字符串变成url对象
        //   let url = urlParams.origin+urlParams.pathname+'/#/withdraw'
        //   location.href = url
        // }
      }
    }
    console.log("微信未绑定");
  } else {
    console.log("已绑定");
  }
};

//绑定微信的内容完了。
const endDateStr = computed(() => formatMonthDay(endDate.value, "YYYY,MM,DD"));
const startDate1 = ref(startDateStr.value.split(","));
const endDate1 = ref(endDateStr.value.split(","));
const showPicker = ref(false);
const start_time = ref(""); //传给后台的参数
const end_time = ref(""); //传给后台的结束时间
const alipayAccount = ref(""); //支付宝账号
let localInfo = localStorage.getItem("userinfo3");
let token = localInfo ? JSON.parse(localInfo).token : "";
const config = reactive({
  highest_money: "",
  minimum_money: "",
  minimum_money: "",
  commission: "",
});
watch([start_time, end_time], (e) => {
  console.log(e[0]);
  if (e[0]) {
    getTimeMoney();
  } else {
    price.value = mainStore.dataCounts.money; //没有的时候默认提现所有
  }
});
const withMoney = async () => {
  let getPrice1 = amountCer(price.value); //验证是否是金额数据
  if (!getPrice1) {
    showToast("提现只能输入数字且最多输入两位小数");
    return;
  }
  let getPrice = Number(price.value);
  // console.log(Number(this.config.minimum_money),'最小金额')
  if (getPrice < Number(config.minimum_money)) {
    showToast("提现金额必须大于最小提现额");
    return;
  }
  // console.log(this.config.highest_money,'最大金额')
  if (getPrice > Number(config.highest_money)) {
    showToast("提现金额必须小于最高提现额");
    return;
  }
  let form = {
    type_data: 0,
    alipayAccount: alipayAccount.value,
    price: getPrice,
    start_time: start_time.value,
    end_time: end_time.value,
  };
  console.log(form, 111);
  let res = await initiate(form);
  showToast("提交成功！");
  getPlateInfo();
};
const getTimeMoney = async () => {
  let res = await getMoney({
    start_time: start_time.value,
    end_time: end_time.value,
  });
  price.value = res.data;
  console.log(res);
};
const onConfirm = () => {
  let startTime = startDate1.value.join("-");
  let endTime = endDate1.value.join("-");
  let dif = getDiffDays(startTime, endTime);
  if (dif < 0) {
    showToast("结束时间必须大于开始时间");
    return;
  }
  dateRange.value = `${startTime} - ${endTime}`;
  start_time.value = startTime;
  end_time.value = endTime;
  showPicker.value = false;
  // showToast(`${} ${endDate1.value.join('/')}`);
};

const getMyConfig = async () => {
  let res = await getConfig();
  config.highest_money = res.data.highest_money;
  config.minimum_money = res.data.minimum_money;
  config.minimum_money = res.data.minimum_money;
  config.commission = res.data.commission;
};
const downExcel = () => {
  if (!downPath) {
    showToast("请先生成对账清单！");
    return;
  }
  if (isWxBrowser()) {
    show.value = true;
    // showToast('请通过浏览器打开下载！')
    return;
  }
  window.location.href = downPath;
};
const onCancel = () => {
  // showToast('cancel');
  price.value = mainStore.dataCounts.money;
  // console.log(price.value,222)
  dateRange.value = ``;
  start_time.value = "";
  end_time.value = "";
  showPicker.value = false;
};
const selectTime = () => {
  showPicker.value = true;
};
const actionList = async () => {
  if (!start_time.value) {
    showToast("请选择时间范围");
    return;
  }
  let res = await reconciliation({
    start_time: start_time.value,
    end_time: end_time.value,
  });
  downPath = res.data;
  showToast("已生成对账清单！");
  console.log(res, "生成对账清单");
};
const getPlateInfo = async () => {
  let res = await getRegionservice();
  mainStore.dataCounts.kabaw_count = res.data.kabaw_count;
  mainStore.dataCounts.order_count = res.data.order_count;
  mainStore.dataCounts.money = res.data.money;
  console.log(mainStore.dataCounts.money, 11);
  price.value = mainStore.dataCounts.money;
};
onMounted(async () => {
  getMyConfig();
  if (token) {
    getPlateInfo();
    await userStore.getInfo();
    getWxInfo();
    // userInfo.value.name = res.data.regionservice.name
    // userInfo.value.service = res.data.mobile
  }
});
// import SearchBar from '@/components/search-bar/search-bar.vue'
</script>

<style lang="scss" scoped>
::v-deep .van-field {
  border: 1px solid #bababa;
}

.withdraw {
  padding: 20px;
  display: flex;
  flex-direction: column;
  color: #1d1b20;
  padding-bottom: 50px;

  .wrapper {
    color: #fff;
    text-align: right;
    padding-right: 20px;
    display: flex;
    justify-content: flex-end;
    align-items: center;

    span {
      font-size: 50px;
      transform: rotate(-32deg);
      margin-left: 10px;
    }
  }

  .selectVal {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 13px;

    .show-box {
      border-radius: 5px;
      border: 0.5px solid #d9d9d9;
      background: #fff;
      padding: 5px 4px;
    }

    .time {
      padding-right: 10px;
    }

    .right {
      display: flex;

      .downList {
        color: #218cc9;
        margin-right: 10px;
        border: 0.5px solid #2cb9a4;
        // background:linear-gradient(to right, #218CC9 0%, #2CB9A4 100%);
      }
    }
  }

  .topTitle {
    margin-left: -24px;
  }

  .borderdiv {
    width: 100%;
    padding: 1px;
    background: linear-gradient(to left,
        transparent 50%,
        #2cb9a4 50%,
        #2cb9a4 100%);
    background-size: 10px 1px;
    /* 第一个参数控制虚线的间隙（利用的是图片的放大效果一样），第二个参数控制虚线的粗细 */
    background-repeat: repeat-x;
    background-position: top;
    margin: 10px 0;
    /* 控制方向：top、bottom */
  }

  .info {
    color: #545454;
    font-family: PingFang SC;
    font-style: normal;
    font-weight: 400;
    line-height: normal;
  }

  .txje {
    width: 100%;
  }

  .item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 30px;
    // color: #828282;

    .jeNum {
      // color: #2CB9A4;
    }

    .txType {
      display: flex;
      align-items: center;

      .useFunc {
        margin: 0 10px;
      }
    }
  }
}
</style>
